<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>前端直传oss demo</title>
    <!-- <link
      href="https://cdn.bootcss.com/weui/2.0.0/style/weui.min.css"
      rel="stylesheet"
    /> -->
    <link
      rel="stylesheet"
      href="http://cdn.suoluomei.com/common/js/css/wpf/weui.css"
    />
  </head>
  <body>
    <div class="weui-cells weui-cells_form" id="uploader">
      <div class="weui-cell">
        <div class="weui-cell__bd">
          <div class="weui-uploader">
            <div class="weui-uploader__hd">
              <p class="weui-uploader__title">图片上传</p>
              <div class="weui-uploader__info">
                <span id="uploadCount">0</span>/9
              </div>
            </div>
            <div class="weui-uploader__bd">
              <ul class="weui-uploader__files" id="uploaderFiles"></ul>
              <div class="weui-uploader__input-box">
                <input
                  id="uploaderInput"
                  class="weui-uploader__input"
                  type="file"
                  accept="image/*"
                  capture="camera"
                  multiple="multiple"
                  onchange="uploadImg(event)"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <script src="https://cdn.bootcss.com/zepto/1.0rc1/zepto.min.js"></script>
    <script>
      window.jQuery = $
      var URL = window.URL || window.webkitURL || window.mozURL
      var apiList = {
        uploadFile:
          'http://ydnshop.hepulanerp.com/sucai_t/public/index.php/post/post/uploadFile',
        label:
          'http://ydnshop.hepulanerp.com/train/public/index.php/api/Mobile/getLabel',
        submit:
          'http://ydnshop.hepulanerp.com/train/public/index.php/api/mobile/setImgScore'
      }
      var defaultParam = {
        uploadKey: 'Gn1xVdBiTClSSHKZifg0pTQSU5XGagWO',
        apiKey: 'yzI2dPfhwI3I6yG^w2i*Oh3targlBaP*'
      }

      var id = 0 // 记录已上传图片数
      var fileinfo = [] // 已上传图片
      var thumbImgArr = [] // 本地预览地址

      /**
       * @description: 上传图片并预览
       * @param {type}
       * @return:
       */
      function uploadImg(e) {
        var files = e.target.files || e.dataTransfer.files
        var imgArr = []
        var sum = files.length + fileinfo.length

        if (sum > 9) {
          alert('图片最多上传9张', 'text')
          return
        }


        for (var i = 0; i < files.length; i++) {
          ;(function(file) {
            if (!/^image/.test(file.type)) {
              $.alert('', '必须上传图片')
              return
            }

            var reader = new FileReader()
            var formData = new FormData()

            reader.onload = function() {
              formData.append('key', defaultParam.uploadKey)
              formData.append('file', file)

              thumbImgArr.push(URL.createObjectURL(file))
              renderUploadImgDom(file)
              // $.showLoading()
              ajaxPostFile(formData, function(data) {
                fileinfo.push(data.info)
                // $.hideLoading()
              })
            }
            reader.readAsArrayBuffer(file)
          })(files[i])
        }
        e.target.value = ''
      }
      /**
       * @description: 预览图片
       * @param {type}
       * @return:
       */
      function renderUploadImgDom(file) {
        $('#uploaderFiles').append(
          '<li class="weui-uploader__file" id="' +
            id +
            '" data-id="' +
            id +
            '" style="background-image:url(' +
            URL.createObjectURL(file) +
            ')"></li>'
        )
        id++
      }

      /**
       * @description: 上传图片
       * @param {type}
       * @return:
       */
      function ajaxPostFile(formData, cb) {
        $.ajax({
          type: 'POST',
          url: apiList.uploadFile,
          processData: false,
          contentType: false,
          data: formData,
          dataType: 'json',
          success: function(resp) {
            cb(resp)
          }
        })
      }

      ;(function($) {
        'use strict'
        // 默认参数
        var defaults = {
          foreground: 'red',
          background: 'yellow'
        }
        $.extend($.fn, {
          ossUpload: function(options) {
            // TODO: 检验传进来的参数
            if(!isValid(options)) {
              return this
            }
            var opts = $.extend({}, defaults, options)

          },
          heightLight: function(options) {
            if(!isValid(options)) {
              return this
            }
            var opts = $.extend({}, defaults, options)
            return this.each(function() {
              var $this = $(this)
              $this.css({
                backgroundColor: opts.background,
                color: opts.foreground
              })
            })
          }

        })
        // 公共方法
        $.fn.getParams = function() {
          return defaults
        }
        // 私有方法，检验参数是否合法
        function isValid(options) {
          return !options || (options && typeof options === 'object') ? true : false
        }
      })(window.$)
    </script>
  </body>
</html>
